
#include <muduo/net/TcpServer.h>
#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <string>
#include <unordered_map>
#include <muduo/base/CountDownLatch.h>
#include <muduo/net/EventLoopThread.h>

class DictClient
{
public:
    DictClient(const std::string& sip, int sport)
        :_downlatch(1),//初始化计数为1.
        _baseloop(_loopthread.startLoop()),
        _client(_baseloop, muduo::net::InetAddress(sip, sport), "DictClient")
        {
            _client.setConnectionCallback(std::bind(&DictClient::onConnection, this, std::placeholders::_1));
            _client.setMessageCallback(std::bind(&DictClient::onMessage, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

            _client.connect();
            //这里是异步操作, 可能连接没有建立成功, 需要等待之后被唤醒.
            _downlatch.wait();
        }

    bool send(const std::string& msg)
    {
        if(_conn->connected() == false)
        {
            std::cout << "连接已断开!" << std::endl;
            return false;
        }
        _conn->send(msg);
        return true;

    }

    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            std::cout << "链接建立成功!" << std::endl;
            _downlatch.countDown();//计数为0被唤醒.
            _conn = conn;
        }
        else
        {
            std::cout << "链接断开" << std::endl;
            _conn.reset();//重置.
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp)
    {
        std::string res = buf->retrieveAllAsString();
        std::cout << res << std::endl;
    }

    
private:
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _downlatch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop* _baseloop;
    muduo::net::TcpClient _client;
};

int main()
{
    DictClient client("127.0.0.1", 9090);
    while(1)
    {
        std::string msg;
        std::cin >> msg;
        client.send(msg);
    }
    return 0;
}

